package com.starlight.ts_clouddev.service.activity;

import com.starlight.ts_clouddev.infrastructure.entity.BlindBox;
import com.starlight.ts_clouddev.infrastructure.entity.Prize;
import com.starlight.ts_clouddev.util.CurrentUserInfoUtils;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author yfy2001
 * @date 2023/6/1 13:53
 */
@Service
public class ActivityService {
    private static final String myName="yanfangyuan202059065205";

    @Resource
    private RedisTemplate<String,List<BlindBox>> redisTemplate;

    /**
     * 盲盒信息存入redis
     * 30天过期
     * 每个月生成随机盲盒
     * 每个盲盒有25%概率中奖
     * 奖品1-12个月的虚拟机时长
     * @return
     */
    public List<BlindBox> generateBlindBox(){
        String userId= CurrentUserInfoUtils.getUserId();
        //根据用户id查询redis中是否已经有盲盒
        List<BlindBox> existList=redisTemplate.opsForValue().get(userId);
        if (existList!=null){
            //盲盒存在直接返回
            return existList;
        }
        //生成新盲盒
        List<String> boxesId=splitString(myName);
        List<BlindBox> blindBoxList=boxesId.stream().map(id->{
                    BlindBox b=new BlindBox();
                    b.setId(id);
                    return b;
                }
        ).toList();
        Random random=new Random();
        for (BlindBox b:blindBoxList) {
            Prize prize=new Prize();
            if (random.nextInt(21)>15){
                b.setHasTruePrize(true);
                long time=random.nextInt(11)+1;
                prize.setDeltaTime(time);
                prize.setDescription("恭喜中奖虚拟机:"+time+"个月。");
            }else {
                b.setHasTruePrize(false);
                prize.setDescription("谢谢惠顾！");
            }
            b.setPrize(prize);
            b.setIsOpened(false);
        }
        redisTemplate.opsForValue().set(userId,blindBoxList, 30,TimeUnit.DAYS);
        return blindBoxList;
    }

    public static List<String> splitString(String targetString) {
        List<String> result = new ArrayList<>();
        Random random = new Random();
        int left=0;
        int right;
        if(random.nextInt()*2>=1){
            right=2;
        } else {
            right=1;
        }
        while(right<targetString.length()){
            result.add(targetString.substring(left,right+1));
            left=right+1;
            if (left==targetString.length()-3){
                result.add(targetString.substring(left,targetString.length()));
                break;
            }
            if(random.nextInt()*2>=1){
                right+=3;
            } else{
                right+=2;
            }
        }
        return result;
    }
}
